package binarycrew.livewallpapers.helpers;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.ByteArrayBuffer;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.net.Uri;
import android.util.Log;
import binarycrew.livewallpapers.Preferences;

public class Http {

	private static final int MAX_PHOTOS = 100;
	private static final String TAG = "ImageManager";

	public static String read(String url) {
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(url);
		HttpResponse response = null;

		try {
			Log.i("HTTP", "Fetch " + url);
			response = client.execute(get);

			if (response.getStatusLine().getStatusCode() == 200) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(
								response.getEntity().getContent()
						)
						);

				String content = "";
				String line = "";

				while ((line = reader.readLine()) != null)
					content += line;

				return content;
			}
			else {
				Log.e("HTTP", "Bad status code " + response.getStatusLine().getStatusCode() + '(' + url + ')');
				return null;
			}
		}
		catch (Exception e) {
			Log.e("HTTP", e.toString());
			return null;
		}
	}

	public static boolean DownloadFromUrl(String imageURL, String fileName, File dir) {
		try {
			URL url = new URL(imageURL);
			File file = new File(dir, fileName);

			long startTime = System.currentTimeMillis();
			Log.d(TAG, "download begining");
			Log.d(TAG, "download url:" + url);
			Log.d(TAG, "downloaded file name:" + fileName);
			Log.d(TAG, "downloaded file:" + file.getAbsolutePath());

			URLConnection ucon = url.openConnection();

			InputStream is = ucon.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is, 8 * 1024);

			ByteArrayBuffer baf = new ByteArrayBuffer(8 * 1024);
			int current = 0;
			while ((current = bis.read()) != -1) {
				baf.append((byte) current);
			}

			FileOutputStream fos = new FileOutputStream(file);
			fos.write(baf.toByteArray());
			fos.close();
			Log.d(TAG,
					"download ready in"
							+ ((System.currentTimeMillis() - startTime) / 1000)
							+ " sec");

			while (dir.list().length > MAX_PHOTOS) {
				File d = new File(dir, dir.list()[(int) (Math.random() * dir.list().length)]);
				if (!d.getName().equals(Preferences.DEFAULT_IMAGE)) {
					Log.d(TAG, "MAX_PHOTOS exceeded, deleting image: " + d.getName());
					d.delete();
				}

			}

			return true;
		}
		catch (Exception e) {
			Log.d(TAG, "Error: " + e);

			return false;
		}
	}

	public static void DownloadImagesFromUrl(Elements galleryImages, File dir) {
		List<String> files = new ArrayList<String>(Arrays.asList(dir.list()));

		for (Element link : galleryImages) {
			Log.e("WALLPAPER", link.attr("src"));
			Uri myUri = Uri.parse(link.attr("src"));
			int size = myUri.getPathSegments().size();
			StringBuilder filename = new StringBuilder();
			if (size > 4) {
				for (int i = 4; i > 0; i--)
					filename.append(myUri.getPathSegments().get(size - i) + "_");
			}
			filename.deleteCharAt(filename.lastIndexOf("_"));

			if (!files.contains(filename.toString()))
			{
				Http.DownloadFromUrl(link.attr("src"), filename.toString(), dir);
			}
			else {
				Log.d("WALLPAPER", "already have image: " + link.attr("src"));
			}
		}
	}

	public static boolean DownloadImageFromUrl(Element galleryImage, File dir) {
		List<String> files = new ArrayList<String>(Arrays.asList(dir.list()));

		Uri myUri = Uri.parse(galleryImage.attr("src"));
		int size = myUri.getPathSegments().size();
		StringBuilder filename = new StringBuilder();
		if (size > 4) {
			for (int i = 4; i > 0; i--)
				filename.append(myUri.getPathSegments().get(size - i) + "_");
		}
		filename.deleteCharAt(filename.lastIndexOf("_"));

		if (!files.contains(filename.toString()))
		{
			return Http.DownloadFromUrl(galleryImage.attr("src"), filename.toString(), dir);
		}
		else {
			Log.d("WALLPAPER", "already have image: " + galleryImage.attr("src"));
			return true;
		}
	}
}
